<template>
<!-- 用户管理 -->
  <div>
    <!-- 搜索/新增 -->
    <div>
      <el-input v-model="formSearch.nickname" placeholder="请输入姓名" class="search"></el-input>
      <el-button type="primary" plain @click="search()">搜索</el-button>
      <el-button @click="reset()">重置</el-button>
      <el-button class="add" type="primary" @click="add()">新增</el-button>
    </div>
    <!-- 列表 -->
    <BaseTable
       :tableData="tableData"
       :loading="loading"
       :clickRow="true"
       :page="page"
       @pageChange="pageChange"
      >
      <el-table-column prop="nickname" label="姓名">
          <template slot-scope="s">
              <el-input v-if="s.row.show === true" v-model="s.row.nickname" maxlength="8"></el-input>
              <span v-else>{{s.row.nickname}}</span>
          </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名">
          <template slot-scope="s">
              <el-input v-if="!s.row._id" v-model="s.row.username" maxlength="8"></el-input>
              <span v-else>{{s.row.username}}</span>
          </template>
      </el-table-column>
      <el-table-column prop="role" label="身份" >
          <template slot-scope="s">
              <el-select v-if="s.row.show === true" v-model="s.row.role">
                    <el-option
                      v-for="item in selectOptions"
                      :key="item.roleId"
                      :label="item.roleName"
                      :value="item.roleName">
                    </el-option>
              </el-select>
              <span v-else>{{s.row.role}}</span>
          </template>
      </el-table-column>
      <el-table-column label="操作" width="300">
        <template slot-scope="s">
          <template v-if="s.row.show === false">
            <el-button size="mini" type="primary" @click="edit(s.row)">编辑</el-button>
            <el-button size="mini" type="info" @click="resetPassword(s.row._id)" :loading='loading'>重置密码</el-button>
            <el-button size="mini" type="danger" class="cell-del-button" @click="remove(s.row._id)" :loading='loading'>删除</el-button>
          </template>
          <template v-else>
            <el-button size="mini" type="primary" @click="save(s.row)" :loading='loading'>保存</el-button>
            <el-button size="mini" type="info" @click="cancel(s.row)">取消</el-button>
          </template>
        </template>
      </el-table-column>
    </BaseTable>
  </div>
</template>

<script>
import { userlist , roleselect ,updateuser ,deluser ,adduser} from '@/api/auth'
export default {
  name: "user",
  data() {
    return {
      tableData: [],
      loading: false,
      formSearch: {
        nickname: '',
      }, 
      page: {
        page: 1,
        limit: 10,
        total: 0
      },
      form: {
        password: 123456
      }, 
      selectOptions: [],
      valRow: {} //'选中操作的数据'
    };
  },
  mounted() {
    this.initData();
    this.getRoleSelect()
  },
  components: {
    BaseTable: () => import("@/components/BaseTable"),
  },
  methods: {
    //添加
    add(){
      //一次只能添加一个
        let obj = {
            username : '',
            password : '',
            nickname : '',
            role: '',
            show: true,
            add: true
        }
        if(this.tableData[0]._id){
          this.tableData.unshift(obj)
        } else {
          this.$message.warning('您正在进行新增操作')
        }
    },
    //编辑
    edit(row){
      console.log(row)
      this.valRow = JSON.parse(JSON.stringify(row))
      row.show = true
    },
    //取消
    cancel(row){
      console.log(row)
      if(!row._id){
        this.tableData.shift()
        return
      }
      //响应式数据用assign方法重置
      row = Object.assign(row,this.valRow)
      this.valRow = {}
    },
    //保存
    save(data){
        const { _id , nickname , role , username} = data
        if(!nickname){
            this.$message.error('昵称不能为空！')
            return
        }
        if(!username){
            this.$message.error('用户名不能为空！')
            return
        }
        if(!role){
            this.$message.error('权限不能为空！')
            return
        }
        data.show = false
        let obj = { nickname,role }
        this.loading = true
        if(!_id){
          console.log(1321321320,data)
          let addform = { nickname, username ,role }
          console.log(addform)
          adduser(addform)
            .then(res => {
                if(res.status && res.status === 200){
                    this.$message.success('新增成功！')
                }
                this.reset()
                this.loading = false
            })
            .catch(()=>{
                this.$message.error('新增失败')
                this.loading = false
            })
          return
        }
        updateuser(_id,obj)
            .then(res=>{
                if(res.status && res.status === 200){
                    this.$message.success('修改成功！')
                }
                this.loading = false
            })
            .catch(()=>{
                this.$message.error('修改失败！')
                this.loading = false
            })
    },
    //列表
    initData() {
     this.loading = true;
     let params = Object.assign(this.page,this.formSearch)
     userlist(params)
       .then((res) => {
        console.log(res)
        if (res.status === 200) {
          let arr = res.data.data;
          arr.forEach(item => {
              item.show = false
          });
          this.tableData = arr
          //注：不能直接给tableData赋值后遍历，否则无法为响应式的数据
          this.page.total = res.data.total;
          console.log(this.tableData,444)
        }
        this.loading = false;
       })
       .catch((err) => {
         this.loading = false;
         this.$message.error("查询数据失败")
       })    
    },
    //搜索
    search(){
      this.page.page = 1 
      this.initData()
    },
    //重置
    reset() {
      this.formSearch.nickname = '';
      this.page.page = 1;
      this.page.total = 0;
      this.initData();
    },
    //分页
    pageChange(val) {
      this.page = val;
      this.initData();
    },
    // 重置密码
    resetPassword(_id) {
      this.$confirm('此操作将重置该用户密码为123456, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        updateuser(_id,this.form)
            .then(res=>{
                if(res.status && res.status === 200){
                    this.$message.success('重置成功！')
                }
                this.loading = false
            })
            .catch(()=>{
                this.$message.error('重置失败！')
                this.loading = false
            })
      }).catch(()=>{})
    },
    //删除用户
    remove(_id) {
      this.$confirm('此操作将删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        deluser(_id)
            .then((res)=>{
                console.log(res,79874654156)
                if(res.status && res.status === 200){
                    this.$message.success("删除该用户成功!");
                }
                this.loading = false;
                this.reset()
            })
            .catch((err) => {
                this.loading = false;
                this.$message.error("删除用户失败")
                this.reset();
            })     
      }).catch(()=>{})
    },
    getRoleSelect(){
        roleselect()
            .then(res => {
                this.selectOptions = res.data.data
            })
            .catch(()=>{
                this.$message.error('获取权限列表失败！')
            })
    }
  }
};
</script>

<style lang="scss" scoped>
.search{
  width: 15%;
  margin-right: 15px;
}
.add{
  float: right;
  margin-right: 25px;
}
</style>